package com.ufenlei.alarm
{
	import flash.desktop.DockIcon;
	import flash.desktop.NativeApplication;
	import flash.desktop.SystemTrayIcon;
	import flash.display.*;
	import flash.events.Event;
	import flash.events.ScreenMouseEvent;
	import flash.net.URLRequest;
	
	import mx.core.WindowedApplication;
	
	public class IconManager
	{
		private var app:WindowedApplication;
		private var sysTrayIcon:SystemTrayIcon;
		private var iconURLs:Array = ["assert/L16.png","assert/L32.png","assert/L48.png","assert/L128.png"];
		private var icons:Array = [];
		public function IconManager(app:WindowedApplication)
		{
			this.app = app;
			this.loadIcons();
		}
		public function set tooltip(s:String):void{
			sysTrayIcon.tooltip = s;
		}
		public function get tooltip():String{
			return sysTrayIcon.tooltip;
		}
		private function initSysTrayIcon():void{
			//不自动退出
			NativeApplication.nativeApplication.autoExit = false;
			//初始化程序菜单
			var iconMenu:NativeMenu = new NativeMenu();
			
			var showMainCommand:NativeMenuItem = iconMenu.addItem(new NativeMenuItem("显示主界面"));
			var exitCommand:NativeMenuItem = iconMenu.addItem(new NativeMenuItem("退出程序"));
			showMainCommand.addEventListener(Event.SELECT,onShowMainSelect);
			exitCommand.addEventListener(Event.SELECT,function(event:Event):void{
				NativeApplication.nativeApplication.icon.bitmaps = [];
				NativeApplication.nativeApplication.exit();
				}
			);
			if(NativeApplication.supportsSystemTrayIcon){
				sysTrayIcon = NativeApplication.nativeApplication.icon as SystemTrayIcon;
				sysTrayIcon.menu = iconMenu;
				sysTrayIcon.tooltip = "定时提醒器";
				sysTrayIcon.addEventListener(ScreenMouseEvent.CLICK,onIconClick);
			}
			if(NativeApplication.supportsDockIcon){
				var dockIcon:DockIcon;
				dockIcon = NativeApplication.nativeApplication.icon as DockIcon;
				dockIcon.menu = iconMenu;
			}
		}
		private function onShowMainSelect(evt:Event):void{
			showMainWindow();
		}
		private function onIconClick(evt:Event):void{
			this.toggleShowMain();
		}
		private function showMainWindow():void{
			app.visible = true;
			app.activate()
		}
		private function toggleShowMain():void{
			if(app.visible){
				app.visible = false;
			}else{
				showMainWindow();
			}
		}
		private function loadIcons():void{
			if(this.iconURLs.length>0){
				var icon:Loader = new Loader();
				icon.contentLoaderInfo.addEventListener(Event.COMPLETE,onIconLoaded);
				icon.load(new URLRequest(this.iconURLs.shift()));
			}else{
				NativeApplication.nativeApplication.icon.bitmaps = this.icons;
				this.initSysTrayIcon();
			}		
		}
		private function onIconLoaded(evt:Event):void{
			this.icons.push(evt.target.content.bitmapData);
			this.loadIcons();
		}
		public function hideIcon():void{
			app.nativeApplication.icon.bitmaps = [];
		}
	}
}